package com.youaishujuhui.devops.web.ws;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.youaishujuhui.devops.web.cache.GlobalCache;
import com.youaishujuhui.devops.web.domain.manage.SysUser;
import com.youaishujuhui.devops.web.util.Common;

public class GlobalWebSocketHandler extends TextWebSocketHandler {
	
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) 
			throws Exception {
		// 接收客户端主动发的消息
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		super.afterConnectionEstablished(session);
		// 连接建立后，把该用户的websocket session缓存起来
		SysUser user = (SysUser) session.getAttributes().get(Common.SESSION_LOGIN_USER_KEY);
		GlobalCache.wsSessionCacheMap.put(user.getUserName(), session);
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		super.handleTransportError(session, exception);
		clean(session);
		System.out.println("handleTransportError");
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		super.afterConnectionClosed(session, status);
		clean(session);
		System.out.println("afterConnectionClosed");
	}
	
	// 清理缓存
	private void clean(WebSocketSession session) {
		SysUser user = (SysUser) session.getAttributes().get(Common.SESSION_LOGIN_USER_KEY);
		if (user != null) {
			GlobalCache.wsSessionCacheMap.remove(user.getUserName());
		}
	}
}
